<?php
namespace app\common\business;

use app\common\lib\Key;
use think\facade\Cache;

class Goods extends BusBase {
    public $model = null;

    public function __construct()
    {
        $this->model = new \app\common\model\mysql\Goods();
    }

    public function getNormalLists($data, $num = 5, $order) {
        try {
            $field = "sku_id as id,title,recommend_image as image,price";
            $list = $this->model->getNormalLists($data, $num, $field, $order);
            $res = $list->toArray();
            $result = [
                'total_page_num'=>isset($res['last_page']) ? $res['last_page'] : 0,
                'count'=>isset($res['total']) ? $res['total'] : 0,
                'page'=>isset($res['current_page']) ? $res['current_page'] : 1,
                'page_size'=>$num,
                'list'=>isset($res['data']) ? $res['data'] : []
            ];
        } catch (\Exception $e) {
            $result = [];
        }
        return $result;
    }

    public function getGoodsDetailBySkuId($skuId) {
        // sku_id sku表 => goods_id goods表 => title image descreption
        // sku => sku数据
        // join
        $skuBisObj = (new GoodsSku());
        $goodsSku = $skuBisObj->getNormalSkuAndGoods($skuId);
        if (empty($goodsSku) || empty($goodsSku['goods'])){
            return [];
        }
        $goods = $goodsSku['goods'];
        $skus = $skuBisObj->getSkusByGoodsId($goods['id']);
        if (empty($skus)){
            return [];
        }

//        $gids = [];
//        foreach ($skus as $sku){
//            $gids[$sku['specs_value_ids']] = $sku['id'];
//        }

        $gids = array_column($skus, 'id', 'specs_value_ids');
        $sku = [];
        $result = [
            'title'=>$goods['title'],
            'price'=>$goodsSku['price'],
            'cost_price'=>$goodsSku['cost_price'],
            'sales_count'=>0,
            'stock'=>$goodsSku['stock'],
            'gids'=>$gids,
            'image'=>$goods['carousel_image'],
            'sku'=>$sku,
            'detail'=>[
                'd1'=>[
                    '商品编码'=>$goodsSku['id'],
                    '上架时间'=>$goods['create_time'],
                ],
                'd2'=>preg_replace('/(<img.+?src=")(.*?)/', '$1'.request()->domain().'$2', $goods['description'])
            ]
        ];
        return $result;
    }
}